<?php

require_once 'Acl/Plugin.php';

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    protected function _initDoctype() {
        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
    }
    
    protected function _initDoctrine() {       
        $cache = new \Doctrine\Common\Cache\ArrayCache();
        
        /**
         * @TODO: Test memcache         
        if (APPLICATION_ENV == "development") {
            $cache = new \Doctrine\Common\Cache\ArrayCache();
        } else {
            $cacheOptions = $options['cache']['backendOptions'];
            $cache = new \Doctrine\Common\Cache\MemcacheCache();
            $memcache = new Memcache();
            $memcache->connect($cacheOptions['servers']['host'], 
            $cacheOptions['servers']['port']);
            $cache->setMemcache($memcache);           
        }
         */
        
        $config = new \Doctrine\ORM\Configuration();
        $config->setMetadataCacheImpl($cache);
        $driverImpl = $config->newDefaultAnnotationDriver(APPLICATION_PATH . '/models');
        $config->setMetadataDriverImpl($driverImpl);
        $config->setQueryCacheImpl($cache);
        $config->setProxyDir(APPLICATION_PATH . '/models/Proxies');
        $config->setProxyNamespace('Proxies');
        
        if (APPLICATION_ENV == "development") {
            $config->setAutoGenerateProxyClasses(true);
        } else {
            $config->setAutoGenerateProxyClasses(false);
        }
        
        $em = \Doctrine\ORM\EntityManager::create($this->getOption('db'), $config);
        Zend_Registry::set('em', $em);
        return $em;        
    }
    
    protected function _initAcl() {
        $roles = Zend_Registry::get('em')->getRepository('Model_Role')->findAll();
        $resources = Zend_Registry::get('em')->getRepository('Model_Resource')->findAll();        
        $permissions = Zend_Registry::get('em')->getRepository('Model_Permission')->findAll();
        
        $acl = new Zend_Acl();
        
        foreach ($roles as $role) {
            $acl->addRole(new Zend_Acl_Role($role->name));
        }
        
        foreach ($resources as $resource) {
            $acl->addResource(new Zend_Acl_Resource($resource->name));
        }
        
        foreach ($permissions as $permission) {
            $acl->allow($permission->role->name, $permission->resource->name, $permission->action);
        }
        
        Zend_Registry::set('acl', $acl);
        
        $front = Zend_Controller_Front::getInstance();
        $front->registerPlugin(new Acl_Plugin());
        
    }
    
}

